package com.songqintuan.common.dal.database;

import java.sql.Connection;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.songqintuan.common.dal.database.DataSourceContextHolder;

public class DBPoolingFactory implements ApplicationContextAware {

	private static ApplicationContext context;
	private static Properties dataSourceMappings;
	private static String DEFAULT_DATA_SOURCE_BEAN_NAME = "dataSource";
	private static final String defaultPoolingDriver = "DefaultDBPoolingDriver";
	private static Log logger = LogFactory.getLog(DBPoolingFactory.class);

	public static Connection getConnection(String poolName) throws Exception {
		String beanName = "dataSource";
		String dataSourceName = "";
		if ("MASTER_DBPoolingDriver".equals(poolName)) {
			// jndiName =
			// ConfigManager.getProperty("deploy.database.master.jndiName");
			// DataSourceContextHolder.setDataSourceType(DataSourceType.MASTER);
			DataSourceContextHolder.setDataSourceType("MASTER");
			// beanName = "accessDataSource";
		} else if ("TntDBPoolingDriver".equals(poolName)) {
			// jndiName =
			// ConfigManager.getProperty("deploy.database.tnt.jndiName");
			// DataSourceContextHolder.setDataSourceType(DataSourceType.TNT);
			DataSourceContextHolder.setDataSourceType("TNT");
			// beanName = "tntDataSource";
		} else {
			// jndiName =
			// ConfigManager.getProperty("deploy.database.fms.jndiName");
			// DataSourceContextHolder.setDataSourceType(DataSourceType.FMS);
			DataSourceContextHolder.setDataSourceType("FMS");
		}

		if (context.containsBean(beanName)) {
			try {
				DataSource ds = (DataSource) context.getBean(beanName,
						DataSource.class);
				return ds.getConnection();
			} catch (NoSuchBeanDefinitionException ex1) {
				if (logger.isDebugEnabled())
					logger.debug("Cannot find bean definition '" + beanName
							+ "'");
			} catch (BeanNotOfRequiredTypeException ex2) {
				if (logger.isDebugEnabled())
					logger.debug("Bean '" + beanName
							+ "' is not a data source.");
			} catch (BeansException ex3) {
				logger.error(null, ex3);
			} finally {
				DataSourceContextHolder.clearDataSourceType();
			}
		}
		return null;
	}

	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		// TODO Auto-generated method stub
		DBPoolingFactory.context = context;
	}
}
